<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="销售人" prop="coachId">
            <el-select v-model="queryParams.coachId" placeholder="请选择" filterable clearable>
              <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName" :value="dict.id"></el-option>
            </el-select>
          </el-form-item>
          <!--        <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="订单数量" prop="orderNum">
            <el-input v-model="queryParams.orderNum" placeholder="请输入订单数量" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="订单价格" prop="orderPrice">
            <el-input v-model="queryParams.orderPrice" placeholder="请输入订单价格" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="三方订单编号" prop="thirdPartyOrderNo">
            <el-input v-model="queryParams.thirdPartyOrderNo" placeholder="请输入三方订单编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付金额" prop="amount">
            <el-input v-model="queryParams.amount" placeholder="请输入支付金额" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付时间" prop="payTime">
            <el-date-picker clearable
              v-model="queryParams.payTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择支付时间"
            />
          </el-form-item> -->
          <!--          <el-form-item label="有效期至" prop="indateTime">
            <el-date-picker clearable
              v-model="queryParams.indateTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择有效期至"
            />
          </el-form-item> -->
          <!--          <el-form-item label="办卡日期" prop="registerCardTime">
            <el-date-picker clearable
              v-model="queryParams.registerCardTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择办卡日期"
            />
          </el-form-item> -->
          <!--          <el-form-item label="销售人，人员信息的主键id" prop="gymUserId">
            <el-input v-model="queryParams.gymUserId" placeholder="请输入销售人，人员信息的主键id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付方式" prop="payMethod">
            <el-input v-model="queryParams.payMethod" placeholder="请输入支付方式" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="开始时间">
            <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD 00:00:00" placeholder="请选择开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker clearable v-model="queryParams.stopTime" type="date" value-format="YYYY-MM-DD 23:59:59" placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item style="margin-left: 10px;">
            <el-button type="primary" @click="handleData">当天</el-button>
            <el-button type="primary" @click="handleDatatime(2)">三日内</el-button>
            <el-button type="primary" @click="handleDatatime(6)">一周内</el-button>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="10" class="card-box">
            <el-card shadow="hover">
              <template #header>
                <PieChart style="width: 1em; height: 1em; vertical-align: middle;" />
                <span style="vertical-align: middle;">销售统计</span>
              </template>
              <div class="el-table el-table--enable-row-hover el-table--medium" v-show="showPie==1">
                <div ref="commandstats" style="height: 400px" />
              </div>
            </el-card>
          </el-col>
          <el-col :span="10" class="card-box">
            <el-card shadow="hover">
              <template #header>
                <PieChart style="width: 1em; height: 1em; vertical-align: middle;" />
                <span style="vertical-align: middle;">销卡类型</span>
              </template>
              <div class="el-table el-table--enable-row-hover el-table--medium" v-show="showPie==1">
                <div ref="usedmemory" style="height: 400px" />
              </div>
            </el-card>
          </el-col>

          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="订单id" align="center" prop="id" v-if="true" />
        <el-table-column label="健身房id" align="center" prop="gymId" /> -->
        <el-table-column label="销售人" align="center" prop="coachName" />
        <el-table-column label="销售时间" align="center" prop="payTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="会员姓名" align="center" prop="memberName" />
        <el-table-column label="会员卡名称" align="center" prop="cardName" />
        <!-- <el-table-column label="订单编号" align="center" prop="orderNo" /> -->
        <el-table-column label="销售类型" align="center">
          <template #default="scope">
            <dict-tag :options="g_market_type" :value="scope.row.marketType" />
          </template>
        </el-table-column>
        <el-table-column label="订单数量" align="center" prop="orderNum" />
        <!-- <el-table-column label="支付金额" align="center" prop="amount" /> -->
        <el-table-column label="订单价格" align="center" prop="orderPrice" />
        <!-- <el-table-column label="三方订单编号" align="center" prop="thirdPartyOrderNo" /> -->

        <!--        <el-table-column label="支付时间" align="center" prop="payTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <!--       <el-table-column label="有效期至" align="center" prop="indateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.indateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <!--        <el-table-column label="订单状态" align="center">
          <template #default="scope">
            <dict-tag :options="orderstats" :value="scope.row.orderStatus" />
          </template>
        </el-table-column> -->
        <!--        <el-table-column label="开卡日期" align="center" prop="registerCardTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.registerCardTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->

        <el-table-column label="支付方式" align="center">
          <template #default="scope">
            <dict-tag :options="g_pay_type" :value="scope.row.payMethod" />
          </template>
        </el-table-column>

        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
                       <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:order:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:order:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="退款审核" placement="top">
              <el-button link type="primary" icon="DataLine" @click="handleRefund(scope.row)" v-hasPermi="['primary:order:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="560px" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="110px">
        <!--    <el-form-item label="健身房id" prop="gymId">
          <el-input v-model="form.gymId" placeholder="请输入健身房id" type="number" :min="0" />
        </el-form-item> -->
        <!--      <el-form-item label="会员卡编号" prop="cardId">
          <el-input v-model="form.cardId" placeholder="请输入会员卡编号" />
        </el-form-item> -->
        <el-form-item label="选择会员卡" prop="cardId">
          <el-select v-model="form.cardId" placeholder="请选择" filterable clearable @change="handleSelectChange">
            <el-option v-for="dict in clubCardLista" :key="dict.id" :label="dict.cardName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择会员" prop="memberId">
          <el-select ref="selectRef" v-model="form.memberId" placeholder="请选择" filterable clearable v-if="isSearch">
            <el-option v-for="dict in memberList" :key="dict.id" :label="dict.memberName" :value="dict.id"></el-option>
          </el-select>
          <el-input v-model="form.memberName" placeholder="请输入会员名进行搜索" type="text" style="width: 215px;" v-else />
          <el-button type="primary" icon="Search" @click="getListvip(form.memberName)">搜索</el-button>
        </el-form-item>
        <!--       <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item> -->
        <el-form-item label="订单数量" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入订单数量" type="number" :min="1" />
        </el-form-item>

        <!--        <el-form-item label="订单价格" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单价格(元)" type="number" :min="0" />
        </el-form-item> -->
        <!--       <el-form-item label="三方订单编号" prop="thirdPartyOrderNo">
          <el-input v-model="form.thirdPartyOrderNo" placeholder="请输入三方订单编号" />
        </el-form-item> -->
        <!--       <el-form-item label="支付金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入支付金额" type="number" :min="0" />
        </el-form-item> -->
        <!--        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable v-model="form.payTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item> -->
        <!--        <el-form-item label="有效期至" prop="indateTime">
          <el-date-picker clearable v-model="form.indateTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期至">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="开卡日期" prop="registerCardTime">
          <!-- <span>{{form.registerCardTime}}</span> -->
          <el-date-picker clearable v-model="form.registerCardTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开卡日期">
          </el-date-picker>
        </el-form-item>

        <!--        <el-form-item label="销售人id" prop="gymUserId">
          <el-input v-model="form.gymUserId" placeholder="请输入销售人，人员信息的主键id" />
        </el-form-item> -->
        <el-form-item label="销售人" prop="coachId" v-if="dialogb.isshowCoach">
          <el-select v-model="form.coachId" placeholder="请选择" :disabled="dialog.isdis" filterable clearable>
            <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="销售类型" prop="marketType">
          <el-select v-model="form.marketType" placeholder="请选择">
            <el-option v-for="item in g_market_type" :key="item.value" :label="item.label" :value="item.value.toString()" />
          </el-select>
        </el-form-item>
        <el-form-item label="赠送时间(天)" prop="giveTime" v-if="dialogb.isshowkecheng">
          <el-input v-model="form.giveTime" placeholder="请输入赠送时间" type="number" :min="0" />
        </el-form-item>
        <!--       <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择">
            <el-option v-for="dict in g_order_type" :key="dict.value" :label="dict.label"
              :value="Number(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="支付方式" prop="payMethod">
          <el-select v-model="form.payMethod" placeholder="请选择">
            <el-option v-for="dict in g_pay_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="退款规则(选填)" prop="gymRefundRuleId">
          <el-select v-model="form.gymRefundRuleId" placeholder="请选择" filterable clearable>
            <el-option v-for="dict in ruleList" :key="dict.id" :label="dict.refundRuleName"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="IC卡号(选填)" prop="icCard" v-if="dialogb.isshowkecheng==false">
          <el-input v-model="form.icCard" placeholder="请输入IC卡号" type="text" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="dialogrefund.title" v-model="dialogrefund.visible" width="500px" append-to-body>
      <el-form ref="orderFormRef" :model="refundInfo" :rules="rules" label-width="110px">
        <el-form-item label="是否同意退款" prop="isRefundCheck">
          <el-select v-model="refundInfo.isRefundCheck" placeholder="请选择" filterable clearable>
            <el-option v-for="dict in refundRule" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="驳回信息(选填)" prop="refundFailReason">
          <el-input v-model="refundInfo.refundFailReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormRefund">确 定</el-button>
          <el-button @click="cancelRefund">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
import { listOrder, getOrder, delOrder, addOrder, updateOrder, addOrderpay, refundOrder, getpie } from '@/api/primary/order';
import { getClubCard } from '@/api/primary/clubCard';
import { listGym } from '@/api/primary/gym';
import { getCache } from '@/api/monitor/cache';
import * as echarts from 'echarts';
import { listClubCard } from '@/api/primary/clubCard';
import { listGymRefundRule } from '@/api/primary/gymRefundRule';
import { ClubCardForm } from '@/api/primary/clubCard/types';
import { listMember } from '@/api/primary/member';
import { OrderVO, OrderQuery, OrderForm } from '@/api/primary/order/types';
import { listRole } from "@/api/system/role";
import { listCoach } from '@/api/primary/coach';
import { watch, nextTick } from 'vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { orderstats, g_pay_type, g_market_type } = toRefs<any>(proxy?.useDict("orderstats", "g_pay_type", "g_market_type"));
const memberList = ref<any>([]);
const ruleList = ref<any>([]);
const clubCardLista = ref<any>([]);
const coachList = ref<any>([]);
const roleCan = ref<any>();
const payinfo = ref<any>({
  id: undefined,
  payMethod: 'CASH'
});
const refundInfo = ref<any>({
  id: undefined,
  isRefundCheck: undefined,
  refundFailReason: undefined,
});
const refundRule = reactive<any>([
  {
    id: 0,
    name: '不通过'
  },
  {
    id: 1,
    name: '通过'
  }]);
const roleList = ref<any>();
const gymList = ref<any>();
const orderList = ref<OrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const isSearch = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selectRef = ref(null);
const dialogb = reactive<DialogOption>({
  isshowkecheng: undefined,
  isshowCoach: undefined
});
const dialogrefund = reactive<DialogOption>({
  visible: false,
  title: '',
});
const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  isdis: 0
});
const initFormData : OrderForm = {
  id: undefined,
  icCard: undefined,
  memberCardId: undefined,
  gymRefundRuleId: undefined,
  giveTime: undefined,
  gymId: undefined,
  memberType: undefined,
  coachId: undefined,
  memberId: undefined,
  cardId: undefined,
  orderNo: undefined,
  orderNum: 1,
  orderPrice: undefined,
  thirdPartyOrderNo: undefined,
  amount: undefined,
  payTime: undefined,
  indateTime: undefined,
  orderStatus: undefined,
  registerCardTime: undefined,
  gymUserId: undefined,
  marketType: undefined,
  memberName: undefined,
  payMethod: undefined
}
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    startTime: undefined,
    startDate: undefined,
    endDate: undefined,
    stopTime: undefined,
    giveTime: undefined,
    creationTime: undefined,
    createTime: '',
    coachId: undefined,
    memberType: undefined,
    memberId: undefined,
    memberName: undefined,
    gymId: undefined,
    userId: undefined,
    cardId: undefined,
    cardName: undefined,
    orderNo: undefined,
    orderNum: undefined,
    orderPrice: undefined,
    thirdPartyOrderNo: undefined,
    amount: undefined,
    payTime: undefined,
    indateTime: undefined,
    orderStatus: undefined,
    registerCardTime: undefined,
    gymUserId: undefined,
    marketType: undefined,
    payMethod: undefined,
    params: {
    }
  },
  rules: {
    userId: [
      { required: false, message: "跟进教练不能为空", trigger: "change" }
    ],
    icCard: [
      { required: false, message: "IC卡号", trigger: "change" }
    ],
    isRefundCheck: [
      { required: true, message: "请选择是否同意", trigger: "change" }
    ],
    cardId: [
      { required: true, message: "会员卡编号不能为空", trigger: "change" }
    ],
    coachId: [
      { required: true, message: "教练不能为空", trigger: "blur" }
    ],
    orderNo: [
      { required: true, message: "订单编号不能为空", trigger: "change" }
    ],
    orderNum: [
      { required: true, message: "订单数量不能为空", trigger: "change" }
    ],
    orderPrice: [
      { required: true, message: "订单价格不能为空", trigger: "change" }
    ],
    // thirdPartyOrderNo: [
    //   { required: true, message: "三方订单编号不能为空", trigger: "change" }
    // ],
    amount: [
      { required: true, message: "支付金额不能为空", trigger: "change" }
    ],
    payTime: [
      { required: true, message: "支付时间不能为空", trigger: "change" }
    ],
    indateTime: [
      { required: true, message: "有效期至不能为空", trigger: "blur" }
    ],
    orderStatus: [
      { required: true, message: "订单状态不能为空", trigger: "change" }
    ],
    registerCardTime: [
      { required: true, message: "办卡日期不能为空", trigger: "blur" }
    ],
    gymUserId: [
      { required: true, message: "销售人不能为空", trigger: "change" }
    ],
    marketType: [
      { required: true, message: "销售类型不能为空", trigger: "change" }
    ],
    memberId: [
      { required: true, message: "", trigger: "blur" }
    ],
    payMethod: [
      { required: true, message: "支付方式", trigger: "change" }
    ]
  }
});
const { queryParams, form, rules } = toRefs(data);
/** 查询会员卡信息列表 */
const getListcard = async () => {

  const res = await listClubCard(queryParams.value);
  clubCardLista.value = res.rows;
  console.log(clubCardLista.value, '会员卡列表')

}
watch(() => form.value.memberId, (newVal, oldVal) => {
  if (newVal == '') {
    isSearch.value = false
    form.value.memberName = ''
  }
});
const cache = ref<any>({});
const commandstats = ref();
const usedmemory = ref();
const showPie = ref(1);
const getListpie = async () => {
  queryParams.value.pageNum = undefined
  queryParams.value.pageSize = undefined

  queryParams.value.startDate = queryParams.value.startTime
  queryParams.value.endDate = queryParams.value.stopTime
  proxy?.$modal.loading("正在加载缓存数据，请稍候！");
  const res = await getpie(queryParams.value);
  proxy?.$modal.closeLoading();
  cache.value = res.data;
  if (cache.value == null) {
    showPie.value = 0
  } else {
    showPie.value = 1
  }
  console.log(showPie.value, 'showPieshowPieshowPie')
  console.log(cache.value.summaryList, 'aaaaaaaaaaaaaaa')
  // 转换数据格式
  const transformedData = cache.value.summaryList.map(item => {
    return { value: item.totalAmount, name: `${item.cardName}  数量:${item.count}张  金额:${item.totalAmount}元` };
  });
  console.log(transformedData, 'transformedDatatransformedDatatransformedData')
  const commandstatsIntance = echarts.init(commandstats.value, "macarons");
  commandstatsIntance.setOption({
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}({d}%)"
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      formatter: function (name) {
        // 分解名称和数据
        let parts = name.split('  ');
        return `{a|${parts[0]}}{b|${parts[1]}}{c|${parts[2]}}`;
      },
      textStyle: {
        rich: {
          a: {
            width: 120,
            align: 'left'
          },
          b: {
            width: 80,
            align: 'left'
          },
          c: {
            width: 80,
            align: 'left'
          }
        }
      }
    },
    series: [
      {
        name: "统计",
        type: "pie",
        radius: [40, 95],
        data: transformedData,
        center: ['25%', '50%'], // 修改这里调整饼图的位置，使其靠左显示
        // stillShowZeroSum: false,
        // avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        // emphasis: {
        //   label: {
        //     show: true,
        //     fontSize: '20'

        //   }
        // },
        labelLine: {
          show: true
        },
        animationDuration: 1000
      }
    ]
  });
  // 转换数据格式
  const transformedDataType = cache.value.newList.map(item => {
    // 使用三元表达式来判断显示"新卡"还是"续卡"
    const cardType = item.cardName == 0 ? "新卡" : "续卡";
    return {
      value: item.totalAmount,
      name: `${cardType}  数量:${item.count}张  金额:${item.totalAmount}元`
    };
  });
  const usedmemoryInstance = echarts.init(usedmemory.value, "macarons");
  usedmemoryInstance.setOption({
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}({d}%)"
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      formatter: function (name) {
        // 分解名称和数据
        let parts = name.split('  ');
        return `{a|${parts[0]}}{b|${parts[1]}}{c|${parts[2]}}`;
      },
      textStyle: {
        rich: {
          a: {
            width: 80,
            align: 'left'
          },
          b: {
            width: 80,
            align: 'left'
          },
          c: {
            width: 80,
            align: 'left'
          }
        }
      }
    },
    series: [
      {
        name: "统计",
        type: "pie",
        radius: [40, 95],
        data: transformedDataType,
        center: ['25%', '50%'], // 修改这里调整饼图的位置，使其靠左显示
        // stillShowZeroSum: false,
        // avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        // emphasis: {
        //   label: {
        //     show: true,
        //     fontSize: '20'

        //   }
        // },
        labelLine: {
          show: true
        },
        animationDuration: 1000
      }
    ]
  });
  window.addEventListener("resize", () => {
    commandstatsIntance.resize()
    usedmemoryInstance.resize()
  });
}

// const handleSelectChange = (selectedId) => {
//   coachList.value = undefined
//   let selectedDict = clubCardLista.value.find(dict => dict.id === selectedId);
//   if (selectedDict) {
//     console.log('Selected memberCourseType:0会员 1课程', selectedDict.memberCourseType);
//     console.log('Selected cardType:卡种;0期限卡 1次卡', selectedDict.cardType);
//     let cardId = selectedDict.id
//     console.log(cardId, '选中的会员卡信息');
//     if (selectedDict.memberCourseType == 1) {
//       getcoach(cardId)
//     }

//     if (selectedDict.memberCourseType == 0) {
//       form.value.coachId = ''
//       dialogb.isshowCoach = false
//     } else {
//       form.value.coachId = ''
//       dialogb.isshowCoach = true
//     }
//     //卡种;0期限卡 1次卡',
//     if (selectedDict.cardType == 1) {
//       form.value.giveTime = ''
//       dialogb.isshowkecheng = false
//     } else {
//       form.value.giveTime = ''
//       dialogb.isshowkecheng = true
//     }

//   }
// }
// /** 课程卡教练列表 */
// const getcoach = async (e ?: any) => {
//   const _id = e
//   const res = await getClubCard(_id);
//   coachList.value = res.data.coaches;
//   console.log(coachList.value, '教练信息表')
// }
/** 查询健身房信息列表 */
const getListgym = async () => {
  const res = await listGym(queryParams.value);
  gymList.value = res.rows;

}
/** 查询会员信息列表 */
const getListvip = async () => {
  console.log(form.value.memberName, 'form.value.memberNameform.value.memberName')
  if (form.value.memberName == undefined) {
    proxy?.$modal.msgSuccess("请先输入会员名再进行搜索");
    return
  }
  const res = await listMember(form.value);
  memberList.value = res.rows;


  console.log(memberList.value, '正式会员表')
  if (memberList.value.length == 0) {
    isSearch.value = false
    proxy?.$modal.msgError("未搜索到该会员，请重新搜索");
  } else {

    isSearch.value = true
    openSelectDropdown()
    proxy?.$modal.msgSuccess("请选择匹配到的会员");
  }

}
function openSelectDropdown() {
  nextTick(() => {
    if (selectRef.value) {
      selectRef.value.focus(); // 这将打开下拉选择框
    }
  });
}
/** 查询退款规则列表 */
const getListrule = async () => {

  const res = await listGymRefundRule(queryParams.value);
  ruleList.value = res.rows;
  console.log(ruleList.value, '正式会员表')

}
// 全部教练表
const getListb = async () => {

  const res = await listCoach();
  coachList.value = res.rows;
  console.log(coachList.value, '教练信息表')

}





/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  dialogb.isshowkecheng = undefined
  dialogb.isshowCoach = undefined
}

/** 取消按钮 */
const cancelRefund = () => {
  reset();
  dialogrefund.visible = false;

}
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  orderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.creationTime = undefined
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  getList();
  getListpie()
}
/** 当日按钮操作 */
const handleData = () => {
  queryParams.value.startTime = undefined
  queryParams.value.stopTime = undefined
  queryParams.value.startDate = undefined
  queryParams.value.endDate = undefined
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  const date = new Date();
  const createISOString = date.toISOString();
  const create = createISOString.split('T')[0];
  queryParams.value.creationTime = create
  getList();
  getListpie()
}
/** 三日与一周按钮操作 */
const handleDatatime = (e) => {
  console.log(e, 'eeeeeeeeee')
  queryParams.value.creationTime = undefined
  queryParams.value.startDate = undefined
  queryParams.value.endDate = undefined
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  // 获取当前日期
  const currentDate = new Date();
  // 设置开始日期为当前日期前2天
  const startOfPeriod = new Date(currentDate);
  startOfPeriod.setDate(currentDate.getDate() - e); // 当天算一天，再往前两天
  // 设置结束日期为当前日期
  const endOfPeriod = new Date(currentDate);

  // 将日期格式转换为 ISO 8601 格式的字符串
  const startISOString = startOfPeriod.toISOString();
  const endISOString = endOfPeriod.toISOString();
  // 提取日期部分，忽略时间部分
  const start = startISOString.split('T')[0];
  const end = endISOString.split('T')[0];
  // 将日期格式从 yyyy-mm-dd 转换为 yyyy-mm-dd 00:00:00
  let formattedStartDate = start + ' 00:00:00';
  let formattedEndDate = end + ' 23:59:59';
  queryParams.value.startTime = formattedStartDate
  queryParams.value.stopTime = formattedEndDate

  console.log("从当天起往前数3天内的开始日期是：" + queryParams.value.startTime);
  console.log("从当天起往前数3天内的结束日期是：" + queryParams.value.stopTime);
  getList();
  getListpie()
}

/** 查询订单信息列表 */
const getList = async () => {
  console.log(queryParams.value, '~~~~~~~~~~~~~~~~')
  loading.value = true;
  const res = await listOrder(queryParams.value);
  orderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.startTime = undefined
  queryParams.value.stopTime = undefined

  queryParams.value.creationTime = undefined
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection : OrderVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.isdis = false
  dialog.visible = true;
  isSearch.value = false
  dialog.title = "添加订单信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row ?: OrderVO) => {
  reset();
  dialog.isdis = true
  const _id = row?.id || ids.value[0]
  const res = await getOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  isSearch.value = false;
  dialog.title = "修改订单信息";
}

/** 审核操作 */
const handleRefund = async (row ?: OrderVO) => {
  reset();
  // const _id = row?.id || ids.value[0]
  // const res = await getOrder(_id);
  // Object.assign(form.value, res.data);
  refundInfo.value.id = row.id
  dialogrefund.visible = true;
  dialogrefund.title = "退款审核";
}
/** 提交按钮 */
const submitFormRefund = async () => {
  buttonLoading.value = true;
  await refundOrder(refundInfo.value).finally(() => buttonLoading.value = false);
  proxy?.$modal.msgSuccess("审核成功");
  dialogrefund.visible = false;
  await getList();
}



/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value?.validate(async (valid : boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateOrder(form.value).finally(() => buttonLoading.value = false);
        proxy?.$modal.msgSuccess("修改成功");
      } else {
        if (form.value.payMethod == '0') {
          form.value.payMethod = 'SCANPAY'
          payinfo.value.payMethod = 'SCANPAY'
        }
        if (form.value.payMethod == '1') {
          payinfo.value.payMethod = 'CASH'
          form.value.payMethod = 'CASH'
        }
        form.value.gymId = gymList.value[0].id
        console.log(form.value.gymId, '~~~~~~~@@@@@@@@@@@@~~~~~')
        const res = await addOrder(form.value).finally(() => buttonLoading.value = false);
        payinfo.value.id = res.data.id
        console.log(payinfo.value.id, 'ssssssssssssssssss')
        await addOrderpay(payinfo.value).finally(() => buttonLoading.value = false);
        proxy?.$modal.msgSuccess("下单成功");
        queryParams.value.cardId = ''
        queryParams.value.memberId = ''
      }

      dialog.visible = false;
      dialogb.isshowkecheng = undefined
      dialogb.isshowCoach = undefined
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row ?: OrderVO) => {
  const _ids = row?.id || ids.value;
  let name = row.cardId
  await proxy?.$modal.confirm('是否确认删除订单信息编号为"' + name + '"的数据项？').finally(() => loading.value = false);
  await delOrder(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('primary/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  queryParams.value.pageNum = undefined
  queryParams.value.pageSize = undefined
  getListpie()
  getListcard()
  getListb()
  // getListvip()
  getListrule()
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 10
  getList();
  getListgym()

});
</script>
